// 系统接口

package api

import (
    "os"
    "fmt"
    "net"

    "net/http"
    "io/ioutil"
    "encoding/json"

    "tokyo/common"
)


// 打印Hello World
func SystemHello(w http.ResponseWriter, r *http.Request)  {
    // 可响应GET方法
    fmt.Println("Hello World!")

    // 打印hostname
    hostName, _ := os.Hostname()
    fmt.Printf("hostName: %s\n", hostName)

    // 打印ip
    nslookup, _ := net.LookupHost(hostName)
    for _, ip := range nslookup {
        fmt.Printf("IP: %s\n", ip)
    }
}

// 接收答案
func GetAnswer(w http.ResponseWriter, r *http.Request)  {
    // 获取调用方法
    method := r.Method

    // 获取内容类型
    contentType := r.Header.Get("Content-Type")

    // 只响应post-json
    if (method == "POST" && contentType == "application/json") {
        // 获取请求体
        b, _ := ioutil.ReadAll(r.Body)

        // 反序列化
        var answer common.Answer
        json.Unmarshal(b, &answer)

        fmt.Println("收到答案！")
        fmt.Println("NodeIp:", answer.NodeIp)
        fmt.Println("Seq:", answer.Seq)
        fmt.Println("DarkText:", answer.DarkText)
        fmt.Println("AskTime:", answer.AskTime)
        fmt.Println("Answer:", answer.Answer)
        fmt.Println("AnswerTime:", answer.AnswerTime)

        // 验证答案，并广播通知节点
        // 211227注：API的响应逻辑都应该做成异步方法，不能耽误别人获取响应结果
        go VerifyAnswer(answer)

        // 返回一个调用成功状态
        fmt.Fprintf(w, "success")
    } else {
        // 返回一个调用失败状态
        fmt.Fprintf(w, "failed")
    }
}
